<template>
  <div class="rental-tracking">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" ref="searchForm" class="search-form">
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="searchForm.licensePlate" placeholder="请输入车牌号" clearable></el-input>
        </el-form-item>
        <el-form-item label="租赁状态" prop="rentalStatus">
          <el-select v-model="searchForm.rentalStatus" placeholder="请选择租赁状态" clearable>
            <el-option v-for="item in rentalStatusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="租期预警" prop="expiryWarning">
          <el-select v-model="searchForm.expiryWarning" placeholder="请选择预警状态" clearable>
            <el-option v-for="item in warningOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card total-card">
          <div slot="header" class="clearfix">
            <span>车辆总数</span>
          </div>
          <div class="stat-value">{{ stats.totalVehicles }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card rented-card">
          <div slot="header" class="clearfix">
            <span>在租车辆</span>
          </div>
          <div class="stat-value">{{ stats.rentedVehicles }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card warning-card">
          <div slot="header" class="clearfix">
            <span>即将到期</span>
          </div>
          <div class="stat-value">{{ stats.expiringVehicles }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card overdue-card">
          <div slot="header" class="clearfix">
            <span>已超期</span>
          </div>
          <div class="stat-value">{{ stats.overdueVehicles }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <div class="table-header">
        <el-button type="primary" icon="el-icon-message" :disabled="selectedRows.length === 0" @click="handleBatchRemind">批量提醒</el-button>
        <el-button type="success" icon="el-icon-document-copy" :disabled="selectedRows.length === 0" @click="handleBatchRenew">批量续租</el-button>
        <el-button type="warning" icon="el-icon-s-finance" :disabled="selectedRows.length === 0" @click="handleBatchCalcFee">计算费用</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :row-class-name="getRowClassName"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="vehicleId" label="车辆ID" width="80" align="center"></el-table-column>
        <el-table-column prop="licensePlate" label="车牌号" width="120" align="center"></el-table-column>
        <el-table-column prop="vehicleName" label="车辆名称" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="customerName" label="租客姓名" width="120" align="center"></el-table-column>
        <el-table-column prop="customerPhone" label="联系电话" width="140" align="center"></el-table-column>
        <el-table-column prop="orderId" label="订单号" width="150" align="center"></el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="170" align="center"></el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="170" align="center"></el-table-column>
        <el-table-column label="剩余租期" width="140" align="center">
          <template slot-scope="scope">
            <span :class="getRemainingClass(scope.row)">{{ getRemainingTime(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="租赁状态" width="120" align="center">
          <template slot-scope="scope">
            <el-tag :type="getRentalStatusType(scope.row.rentalStatus)">
              {{ getRentalStatusLabel(scope.row.rentalStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              type="primary" 
              icon="el-icon-message" 
              @click="handleRemind(scope.row)"
              :disabled="scope.row.rentalStatus !== 1 && scope.row.rentalStatus !== 2"
            >提醒</el-button>
            <el-button 
              size="mini" 
              type="success" 
              icon="el-icon-document-copy" 
              @click="handleRenew(scope.row)"
              :disabled="scope.row.rentalStatus !== 1"
            >续租</el-button>
            <el-button 
              size="mini" 
              type="warning" 
              icon="el-icon-s-finance" 
              @click="handleCalcFee(scope.row)"
              :disabled="scope.row.rentalStatus !== 2"
            >计算费用</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageParams.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 续租对话框 -->
    <el-dialog title="续租" :visible.sync="renewDialogVisible" width="500px">
      <el-form :model="renewForm" :rules="renewRules" ref="renewForm" label-width="100px">
        <el-form-item label="车牌号">
          <span>{{ renewForm.licensePlate }}</span>
        </el-form-item>
        <el-form-item label="租客姓名">
          <span>{{ renewForm.customerName }}</span>
        </el-form-item>
        <el-form-item label="当前到期时间">
          <span>{{ renewForm.currentEndTime }}</span>
        </el-form-item>
        <el-form-item label="续租天数" prop="days">
          <el-input-number v-model="renewForm.days" :min="1" :max="90"></el-input-number>
        </el-form-item>
        <el-form-item label="新到期时间">
          <span>{{ getNewEndTime(renewForm.currentEndTime, renewForm.days) }}</span>
        </el-form-item>
        <el-form-item label="续租费用">
          <span class="price">¥ {{ calculateRenewFee(renewForm.days, renewForm.dailyRent) }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="renewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRenew('renewForm')">确认续租</el-button>
      </div>
    </el-dialog>

    <!-- 费用计算对话框 -->
    <el-dialog title="超期费用计算" :visible.sync="feeDialogVisible" width="500px">
      <el-form :model="feeForm" ref="feeForm" label-width="120px">
        <el-form-item label="车牌号">
          <span>{{ feeForm.licensePlate }}</span>
        </el-form-item>
        <el-form-item label="租客姓名">
          <span>{{ feeForm.customerName }}</span>
        </el-form-item>
        <el-form-item label="应还时间">
          <span>{{ feeForm.endTime }}</span>
        </el-form-item>
        <el-form-item label="当前时间">
          <span>{{ getCurrentTime() }}</span>
        </el-form-item>
        <el-form-item label="超期时长">
          <span class="overdue">{{ calculateOverdueTime(feeForm.endTime) }}</span>
        </el-form-item>
        <el-form-item label="日租金">
          <span>¥ {{ feeForm.dailyRent }}</span>
        </el-form-item>
        <el-form-item label="超期费率">
          <span>{{ feeForm.overdueRate }}倍</span>
        </el-form-item>
        <el-form-item label="超期费用">
          <span class="price">¥ {{ calculateOverdueFee(feeForm.endTime, feeForm.dailyRent, feeForm.overdueRate) }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="feeDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleSendOverdueNotice">发送催缴通知</el-button>
      </div>
    </el-dialog>

    <!-- 提醒对话框 -->
    <el-dialog title="发送提醒" :visible.sync="remindDialogVisible" width="500px">
      <el-form :model="remindForm" :rules="remindRules" ref="remindForm" label-width="100px">
        <el-form-item label="提醒方式" prop="remindType">
          <el-radio-group v-model="remindForm.remindType">
            <el-radio :label="1">短信</el-radio>
            <el-radio :label="2">电话</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="提醒内容" prop="content">
          <el-input type="textarea" v-model="remindForm.content" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="remindDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRemind('remindForm')">发送提醒</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { parseTime, formatTime } from '@/utils/index'

export default {
  name: 'RentalStatusTracking',
  data() {
    return {
      // 搜索表单
      searchForm: {
        licensePlate: '',
        rentalStatus: '',
        expiryWarning: ''
      },
      // 分页参数
      pageParams: {
        current: 1,
        size: 10
      },
      // 表格数据
      tableData: [],
      total: 0,
      loading: false,
      selectedRows: [],
      // 统计数据
      stats: {
        totalVehicles: 0,
        rentedVehicles: 0,
        expiringVehicles: 0,
        overdueVehicles: 0
      },
      // 续租对话框
      renewDialogVisible: false,
      renewForm: {
        id: null,
        licensePlate: '',
        customerName: '',
        currentEndTime: '',
        days: 1,
        dailyRent: 0
      },
      renewRules: {
        days: [
          { required: true, message: '请输入续租天数', trigger: 'blur' },
          { type: 'number', min: 1, max: 90, message: '续租天数范围为1-90天', trigger: 'blur' }
        ]
      },
      // 费用计算对话框
      feeDialogVisible: false,
      feeForm: {
        id: null,
        licensePlate: '',
        customerName: '',
        endTime: '',
        dailyRent: 0,
        overdueRate: 1.5
      },
      // 提醒对话框
      remindDialogVisible: false,
      remindForm: {
        ids: [],
        remindType: 1,
        content: ''
      },
      remindRules: {
        remindType: [{ required: true, message: '请选择提醒方式', trigger: 'change' }],
        content: [{ required: true, message: '请输入提醒内容', trigger: 'blur' }]
      },
      // 选项
      rentalStatusOptions: [
        { value: 0, label: '未租赁' },
        { value: 1, label: '租赁中' },
        { value: 2, label: '已超期' }
      ],
      warningOptions: [
        { value: 0, label: '正常' },
        { value: 1, label: '即将到期' },
        { value: 2, label: '已超期' }
      ]
    }
  },
  created() {
    this.fetchData()
    this.fetchStats()
  },
  methods: {
    // 获取租赁状态数据
    fetchData() {
      this.loading = true
      const params = {
        current: this.pageParams.current,
        size: this.pageParams.size,
        ...this.searchForm
      }
      
      request({
        url: '/car-rental/rental-status/page',
        method: 'get',
        params
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 获取统计数据
    fetchStats() {
      request({
        url: '/car-rental/rental-status/stats',
        method: 'get'
      }).then(res => {
        this.stats = res.data
      })
    },
    // 处理搜索
    handleSearch() {
      this.pageParams.current = 1
      this.fetchData()
    },
    // 重置搜索
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.handleSearch()
    },
    // 处理选择变更
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    // 处理页码变更
    handleCurrentChange(current) {
      this.pageParams.current = current
      this.fetchData()
    },
    // 处理每页数量变更
    handleSizeChange(size) {
      this.pageParams.size = size
      this.pageParams.current = 1
      this.fetchData()
    },
    // 计算剩余租期
    getRemainingTime(row) {
      if (!row.endTime || row.rentalStatus === 0) {
        return '-'
      }
      
      const now = new Date()
      const endTime = new Date(row.endTime)
      const diff = endTime - now
      
      if (diff <= 0) {
        const overdueDays = Math.ceil(Math.abs(diff) / (1000 * 60 * 60 * 24))
        return `超期 ${overdueDays} 天`
      }
      
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      
      return `${days}天${hours}小时`
    },
    // 获取剩余租期的样式
    getRemainingClass(row) {
      if (!row.endTime || row.rentalStatus === 0) {
        return ''
      }
      
      const now = new Date()
      const endTime = new Date(row.endTime)
      const diff = endTime - now
      
      if (diff <= 0) {
        return 'overdue'
      }
      
      const hours = diff / (1000 * 60 * 60)
      
      if (hours <= 24) {
        return 'warning'
      }
      
      return 'normal'
    },
    // 获取租赁状态标签样式
    getRentalStatusType(status) {
      const map = {
        0: 'info',
        1: 'success',
        2: 'danger'
      }
      return map[status] || 'info'
    },
    // 获取租赁状态名称
    getRentalStatusLabel(status) {
      const found = this.rentalStatusOptions.find(item => item.value === status)
      return found ? found.label : '未知'
    },
    // 获取行样式类名
    getRowClassName({ row }) {
      if (row.rentalStatus === 2) {
        return 'overdue-row'
      }
      
      if (!row.endTime || row.rentalStatus === 0) {
        return ''
      }
      
      const now = new Date()
      const endTime = new Date(row.endTime)
      const diff = endTime - now
      const hours = diff / (1000 * 60 * 60)
      
      if (hours <= 24 && hours > 0) {
        return 'warning-row'
      }
      
      return ''
    },
    // 处理提醒
    handleRemind(row) {
      this.remindDialogVisible = true
      this.remindForm = {
        ids: [row.id],
        remindType: 1,
        content: this.getDefaultRemindContent(row)
      }
    },
    // 批量提醒
    handleBatchRemind() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要提醒的记录')
        return
      }
      
      this.remindDialogVisible = true
      this.remindForm = {
        ids: this.selectedRows.map(row => row.id),
        remindType: 1,
        content: this.getDefaultRemindContent(this.selectedRows[0])
      }
    },
    // 获取默认提醒内容
    getDefaultRemindContent(row) {
      if (!row) return ''
      
      if (row.rentalStatus === 2) {
        return `尊敬的${row.customerName}客户，您租赁的车辆（${row.licensePlate}）已超期，请尽快归还车辆或办理续租手续，以免产生更多超期费用。如有疑问，请联系我们的客服。`
      }
      
      const endTime = new Date(row.endTime)
      const now = new Date()
      const diff = endTime - now
      const hours = diff / (1000 * 60 * 60)
      
      if (hours <= 24 && hours > 0) {
        return `尊敬的${row.customerName}客户，您租赁的车辆（${row.licensePlate}）将在${Math.floor(hours)}小时后到期，请您做好归还准备。如需续租，请提前办理续租手续。如有疑问，请联系我们的客服。`
      }
      
      return `尊敬的${row.customerName}客户，您租赁的车辆（${row.licensePlate}）将于${formatTime(row.endTime)}到期，请您注意租期并及时归还车辆。如需续租，请提前办理续租手续。`
    },
    // 提交提醒
    submitRemind(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          request({
            url: '/car-rental/rental-status/remind',
            method: 'post',
            data: this.remindForm
          }).then(() => {
            this.$message.success('提醒发送成功')
            this.remindDialogVisible = false
          })
        }
      })
    },
    // 处理续租
    handleRenew(row) {
      this.renewDialogVisible = true
      this.renewForm = {
        id: row.id,
        licensePlate: row.licensePlate,
        customerName: row.customerName,
        currentEndTime: row.endTime,
        days: 1,
        dailyRent: row.dailyRent || 0
      }
    },
    // 批量续租
    handleBatchRenew() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要续租的记录')
        return
      }
      
      // 过滤出可以续租的记录（租赁中的）
      const rentingRows = this.selectedRows.filter(row => row.rentalStatus === 1)
      if (rentingRows.length === 0) {
        this.$message.warning('所选记录中没有可续租的记录')
        return
      }
      
      this.$message.info(`选中了${rentingRows.length}条记录，请逐个操作`)
      this.handleRenew(rentingRows[0])
    },
    // 计算续租后的新到期时间
    getNewEndTime(currentEndTime, days) {
      if (!currentEndTime) return ''
      
      const date = new Date(currentEndTime)
      date.setDate(date.getDate() + days)
      return formatTime(date)
    },
    // 计算续租费用
    calculateRenewFee(days, dailyRent) {
      return (days * dailyRent).toFixed(2)
    },
    // 提交续租
    submitRenew(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          request({
            url: '/car-rental/rental-status/renew',
            method: 'post',
            data: this.renewForm
          }).then(() => {
            this.$message.success('续租成功')
            this.renewDialogVisible = false
            this.fetchData()
          })
        }
      })
    },
    // 处理超期费用计算
    handleCalcFee(row) {
      this.feeDialogVisible = true
      this.feeForm = {
        id: row.id,
        licensePlate: row.licensePlate,
        customerName: row.customerName,
        endTime: row.endTime,
        dailyRent: row.dailyRent || 0,
        overdueRate: 1.5
      }
    },
    // 批量计算超期费用
    handleBatchCalcFee() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要计算费用的记录')
        return
      }
      
      // 过滤出可以计算超期费用的记录（已超期的）
      const overdueRows = this.selectedRows.filter(row => row.rentalStatus === 2)
      if (overdueRows.length === 0) {
        this.$message.warning('所选记录中没有超期的记录')
        return
      }
      
      this.$message.info(`选中了${overdueRows.length}条记录，请逐个操作`)
      this.handleCalcFee(overdueRows[0])
    },
    // 获取当前时间
    getCurrentTime() {
      return formatTime(new Date())
    },
    // 计算超期时长
    calculateOverdueTime(endTime) {
      if (!endTime) return '-'
      
      const now = new Date()
      const end = new Date(endTime)
      const diff = now - end
      
      if (diff <= 0) {
        return '未超期'
      }
      
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      
      return `${days}天${hours}小时`
    },
    // 计算超期费用
    calculateOverdueFee(endTime, dailyRent, overdueRate) {
      if (!endTime) return '0.00'
      
      const now = new Date()
      const end = new Date(endTime)
      const diff = now - end
      
      if (diff <= 0) {
        return '0.00'
      }
      
      // 超期不足一天按一天计算
      const days = Math.ceil(diff / (1000 * 60 * 60 * 24))
      return (days * dailyRent * overdueRate).toFixed(2)
    },
    // 发送超期缴费通知
    handleSendOverdueNotice() {
      request({
        url: '/car-rental/rental-status/overdue-notice',
        method: 'post',
        data: {
          id: this.feeForm.id,
          overdueFee: this.calculateOverdueFee(this.feeForm.endTime, this.feeForm.dailyRent, this.feeForm.overdueRate)
        }
      }).then(() => {
        this.$message.success('超期缴费通知发送成功')
        this.feeDialogVisible = false
      })
    },
    
    // 生成报表
    generateReport() {
      request({
        url: '/car-rental/rental-status/report',
        method: 'get',
        responseType: 'blob'
      }).then(res => {
        const blob = new Blob([res], { type: 'application/pdf' })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = '车辆租赁状态报表.pdf'
        link.click()
        URL.revokeObjectURL(link.href)
      }).catch(err => {
        console.error('生成报表失败', err)
        this.$message.error('生成报表失败')
      })
    },
    
    // 导出数据
    exportData() {
      const params = {
        licensePlate: this.searchForm.licensePlate,
        rentalStatus: this.searchForm.rentalStatus,
        expiryWarning: this.searchForm.expiryWarning
      }
      
      request({
        url: '/car-rental/rental-status/export',
        method: 'get',
        params,
        responseType: 'blob'
      }).then(res => {
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = '车辆租赁状态数据.xlsx'
        link.click()
        URL.revokeObjectURL(link.href)
      }).catch(err => {
        console.error('导出数据失败', err)
        this.$message.error('导出数据失败')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.rental-tracking {
  .search-card {
    margin-bottom: 20px;
  }
  
  .stat-cards {
    margin-bottom: 20px;
    
    .stat-card {
      text-align: center;
      
      .stat-value {
        font-size: 28px;
        font-weight: bold;
      }
      
      &.total-card .stat-value {
        color: #409EFF;
      }
      
      &.rented-card .stat-value {
        color: #67C23A;
      }
      
      &.warning-card .stat-value {
        color: #E6A23C;
      }
      
      &.overdue-card .stat-value {
        color: #F56C6C;
      }
    }
  }
  
  .table-card {
    .table-header {
      margin-bottom: 20px;
      display: flex;
      justify-content: flex-start;
      
      .el-button {
        margin-right: 10px;
      }
    }
  }
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
  
  .normal {
    color: #67C23A;
  }
  
  .warning {
    color: #E6A23C;
  }
  
  .overdue {
    color: #F56C6C;
  }
  
  .price {
    color: #F56C6C;
    font-weight: bold;
    font-size: 18px;
  }
}

::v-deep .warning-row {
  background-color: rgba(230, 162, 60, 0.1);
}

::v-deep .overdue-row {
  background-color: rgba(245, 108, 108, 0.1);
}
</style> 